var HellaFox = {
    _xmlRpcClient: null,
    _HttpAuthManager: null,
    _timeout: null,

    toggleMsg: function() {
        if (this._timeout != null) {
            clearTimeout(this._timeout);
            this._timeout = null;
        }
        sbl = document.getElementById('hellafox-statusLabel');
        sbl.hidden = !sbl.hidden;
    },

    setMsg: function(msg) {
        if (this._timeout != null) {
            clearTimeout(this._timeout);
            this._timeout = null;
        }
        sbl = document.getElementById('hellafox-statusLabel');
        sblv = document.getElementById('hellafox-statusLabelValue');
        sblv.value = msg;
        sbl.hidden = false;
        var status_delay = HellaFoxPrefs.getStatusDelay();
        if (status_delay > 0) {
            this._timeout = setTimeout(HellaFox.clearMsg, status_delay * 1000);
        }
    },

    clearMsg: function(msg) {
        if (this._timeout != null) {
            clearTimeout(this._timeout);
            this._timeout = null;
        }
        sbl = document.getElementById('hellafox-statusLabel');
        sbl.hidden = true;
    },

    isNewzbinPost: function() {
        if (content.document.location && content.document.location.href &&
            (content.document.location.href.match(/^https?:\/\/(www\.)?newzbin\.com\//i) ||
            content.document.location.href.match(/^https?:\/\/v3\.newzbin\.com\//i) ||
            content.document.location.href.match(/^https?:\/\/(www\.)?newzxxx\.com\//i) ||
            content.document.location.href.match(/^https?:\/\/(editors\.)?newzbin\.com\//i))) {
            var hr = content.document.location.href;
            if ( hr.indexOf("/browse/post/") != -1 ) {
                return true;
            }
        }
        return false;
    },

    isNewzbinPostLink: function() {
        var href = null;
        if (!gContextMenu.onLink)
            return false;
        if (gContextMenu && gContextMenu.getLinkURL)
            href = gContextMenu.getLinkURL();
        else if (gContextMenu && gContextMenu.linkURL)
            href = gContextMenu.linkURL();
        if (!href)
            return false;
        if (href.match(/^https?:\/\/(www\.)?newzbin\.com\//i) ||
            href.match(/^https?:\/\/v3\.newzbin\.com\//i) ||
            href.match(/^https?:\/\/(www\.)?newzxxx\.com\//i) ||
            href.match(/^https?:\/\/(editors\.)?newzbin\.com\//i)) {
            if (href.indexOf("/browse/post/") != -1 ) {
                return true;
            }
        }
        return false;
    },

    isNZBLink: function() {
        var href = null;
        if (!gContextMenu.onLink)
            return false;
        if (gContextMenu && gContextMenu.getLinkURL)
            href = gContextMenu.getLinkURL();
        else if (gContextMenu && gContextMenu.linkURL)
            href = gContextMenu.linkURL();
        if (!href)
            return false;
        if (href.match(/\.nzb$/i)) {
            return true;
        }
        else if (href.match(/^https?:\/\/(secure\.)?members\.easynews\.com\/zipmanager\.html\?GenNZB=/i) ||
                 href.match(/^https?:\/\/(www\.)?tvnzb\.com\/nzb\/\d+/i) ||
                 href.match(/^https?:\/\/(www\.)?yabse\.com\/createnzb\.php\?[bc]id=\d+/i) ||
                 href.match(/^https?:\/\/(www\.)?nzbindex\.nl\/(index.php)?\?go=nzb/i) ||
                 href.match(/^https?:\/\/(www\.)?nzbindex\.nl\/(index.php)?\?.*&go=nzb/i)) {
            return true;
        }
        return false;
    },

    dlNZBHandler: {
        onResult: function(client, msg, result) {
            var prop_msg = hellafoxBundle.getString("queuedPost");
            HellaFox.setMsg(prop_msg);
        },
        onFault: function (client, ctxt, fault) {
            var prop_msg = hellafoxBundle.getString("xmlRpcFault");
            HellaFox.setMsg(prop_msg + ' ' + fault);
        },
        onError: function (client, ctxt, status, errorMsg) {
            var prop_msg = hellafoxBundle.getString("xmlRpcError");
            HellaFox.setMsg(prop_msg + ' ' + errorMsg);
        }
    },

   dlNZB: function() {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect UniversalBrowserAccess');
        var slurp = null;
        var call_type = null;
        var uri = null;
        var url_port = -1;
        var auth_user = {};
        var auth_pass = {};
        var auth_domain = {};

        if (HellaFox.isNewzbinPost()) {
            slurp = content.window.location.href.match(/\/browse\/post\/(\d+)/i);
            if (!slurp) {
                slurp = content.window.location.href.match(/\/browse\/post\/p\/\?ps_id=(\d+)/i);
            }
            call_type = 'enqueuenewzbin';
        }
        else if (HellaFox.isNewzbinPostLink()) {
            var href = null;
            if (gContextMenu && gContextMenu.getLinkURL)
                href = gContextMenu.getLinkURL();
            else if (gContextMenu && gContextMenu.linkURL)
                href = gContextMenu.linkURL();
            slurp = href.match(/\/browse\/post\/(\d+)/i);
            call_type = 'enqueuenewzbin';
        }
        else if (HellaFox.isNZBLink()) {
            if (gContextMenu && gContextMenu.getLinkURL)
                href = gContextMenu.getLinkURL();
            else if (gContextMenu && gContextMenu.linkURL)
                href = gContextMenu.linkURL();

            uri = Components.classes['@mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI)
            uri.spec = href;
            if (uri.scheme != 'http' && uri.scheme != 'https' && uri.scheme != 'file') {
                HellaFox.setMsg(hellafoxBundle.getString("unsupportedProtocol"));
                return false;
            }
            if (uri.scheme == 'file') {
                call_type = 'enqueue';
            }
            else {
                url_port = uri.port;
                if(url_port == -1) {
                    if(uri.scheme == 'http') {
                        url_port = 80;
                    }
                    else if(uri.scheme == 'https') {
                        url_port = 443;
                    }
                }
                call_type = 'enqueueurl';
                if (!this._HttpAuthManager) {
                    this._HttpAuthManager = Components.classes['@mozilla.org/network/http-auth-manager;1'].createInstance(Components.interfaces.nsIHttpAuthManager);
                }

                try {
                    this._HttpAuthManager.getAuthIdentity(uri.scheme, uri.host, url_port, '', '', uri.path, auth_domain, auth_user, auth_pass);
                    // this._HttpAuthManager.getAuthIdentity(uri.scheme, uri.host, url_port, '', '', '/', auth_domain, auth_user, auth_pass);
                }
                catch (ex) {
                    // alert("uri.scheme = " + uri.scheme + "\n" + "uri.host = " + uri.host + "\n" + "url_port = " + url_port + "\n" + "uri.path = /\n" + "Exception: " + ex.name + " : " + ex.message);
                    auth_domain.value = "";
                    auth_user.value = "";
                    auth_pass.value = "";
                }
            }
        }
        else {
            return false;
        }

        if (!this._xmlRpcClient) {
            this._xmlRpcClient = Components.classes['@mozilla.org/xml-rpc/client;1'].createInstance(Components.interfaces.nsIXmlRpcClient);
        }
        var hostname = HellaFoxPrefs.getHostname();
        var port = HellaFoxPrefs.getPort();
        var password = HellaFoxPrefs.getPassword();

        var tmp_url = 'http://' + hostname + ':' + port + '/';
        this._xmlRpcClient.init(tmp_url);
        this._xmlRpcClient.setAuthentication('hellanzb', password);
        var postId = this._xmlRpcClient.createType(this._xmlRpcClient.STRING,{});
        if (call_type == 'enqueuenewzbin') {
            postId.data = slurp[1];
        }
        else if (call_type == 'enqueue') {
            postId.data = uri.path;
        }
        else {
            if (auth_user.value == "") {
                postId.data = uri.spec;
            }
            else {
                if (url_port == 80 || url_port == 443)
                    postId.data = uri.scheme + '://' + auth_user.value  + ':' + auth_pass.value + '@' + uri.host + uri.path;
                else
                    postId.data = uri.scheme + '://' + auth_user.value  + ':' + auth_pass.value + '@' + uri.host + ':' + url_port + uri.path;
            }
        }
        this._xmlRpcClient.asyncCall(this.dlNZBHandler, null, call_type, [postId], 1);
        return true;
    },

    startup: function() {
        var menu = document.getElementById("contentAreaContextMenu");
        menu.addEventListener("popupshowing", this.contextPopupShowing, false);
        hellafoxBundle = document.getElementById("bundle_hellafox");
    },

    contextPopupShowing: function() {
        var menuitem = document.getElementById('hellafox-context-dlnzb');
        if (menuitem)
            if (HellaFox.isNewzbinPost())
                menuitem.hidden = false;
            else if (HellaFox.isNewzbinPostLink())
                menuitem.hidden = false;
            else if (HellaFox.isNZBLink())
                menuitem.hidden = false;
            else
                menuitem.hidden = true;
    }
};

var hellafoxBundle;
document.addEventListener("DOMContentLoaded", function() { HellaFox.startup(); }, false);
